#!/usr/bin/python
# -*- coding:utf-8 -*-
# @author  : Chestnut
# @time    : 2025/6/24 15:26
# @function: What can I do.
# @version : V1
import datetime
import tkinter
from tkinter import filedialog, ttk
import re
import os
import openpyxl


class TxtCut:
    def __init__(self):
        self.str_source_dir = None
        self.file = None

    def read_file(self):
        self.listbox.delete(0, tkinter.END)
        askdir = filedialog.askdirectory()
        if askdir != "":
            self.str_source_dir.set(askdir)
            self.file_list = os.listdir(askdir)
            for item in self.file_list:
                self.listbox.insert(tkinter.END, item)
        else:
            self.str_source_dir.set("未选择")
            self.listbox.insert(tkinter.END, "None")
            pass

    def set_target(self):
        askdir = filedialog.askdirectory()
        if askdir != "":
            self.str_target_dir.set(askdir)
        else:
            self.str_target_dir.set("未选择")
            pass

    def cut_file(self, alpha=None):
        with open(self.str_source_file.get(), "r", encoding="utf-8") as o_f:
            self.file = o_f.read()
            self.text_prev.insert(tkinter.END, "开始读取" + o_f.name)
            self.text_prev.insert(tkinter.END, "\n")
            self.text_prev.see(tkinter.END)
            if self.str_date.get() != "" and self.str_hour.get() == "" and self.str_minute.get() == "" and self.str_second.get() == "":
                '''自由模式：直接在日期栏写入正则表达式或者想要找到的行（一定是以#作为行首）'''
                self.text_prev.insert(tkinter.END, "正在以自由模式匹配……\n")
                matching = re.search(self.str_date.get() + f"(#.*\n){{{int(self.str_lines.get())}}}", self.file)
                if matching != None:
                    self.result = matching.group()
                    self.text_prev.delete("1.0", tkinter.END)
                    self.text_prev.insert(tkinter.END, self.result)
                    self.text_prev.update()
                else:
                    self.text_prev.insert(tkinter.END, "未匹配到任何数据")
            elif self.str_date.get() == "" and self.str_hour.get() != "" and self.str_minute.get() != "" and self.str_second.get() != "":
                "标准模式：在时间栏填入时分秒（24小时制）即可得到想要的行"
                self.text_prev.insert(tkinter.END, "正在以标准模式匹配……\n")
                matching = re.search(
                    "(#.*)" + self.str_hour.get() + ':' + self.str_minute.get() + ':' + self.str_second.get() + "(.*\n)" + f"(#.*\n){{{self.str_lines.get()}}}",
                    self.file)
                if matching != None:
                    self.result = matching.group()
                    self.text_prev.delete("1.0", tkinter.END)
                    self.text_prev.insert(tkinter.END, self.result)
                    self.text_prev.update()
                else:
                    self.text_prev.insert(tkinter.END, "未匹配到任何数据")
            elif self.str_date.get() != "" and self.str_hour.get() != "" and self.str_minute.get() != "" and self.str_second.get() != "":
                "扩展模式：在日期栏填入日期(yyyy-mm-dd)，并在时间栏填入时分秒（24小时制）即可得到想要的行"
                self.text_prev.insert(tkinter.END, "正在以扩展模式匹配……\n")
                matching = re.search(
                    "(#.*)" + self.str_date.get() + " " + self.str_hour.get() + ':' + self.str_minute.get() + ':' + self.str_second.get() + "(.*\n)" + f"(#.*\n){{{int(self.str_lines.get())}}}",
                    self.file)
                if matching != None:
                    self.result = matching.group()
                    self.text_prev.delete("1.0", tkinter.END)
                    self.text_prev.insert(tkinter.END, self.result)
                    self.text_prev.update()
                else:
                    self.text_prev.insert(tkinter.END, "未匹配到任何数据,开始尝试第二次匹配\n")
                    date_str_list = self.str_date.get().split("-")
                    matching = re.search(
                        "(#.*)" + date_str_list[
                            2] + " Jun 2025" + "(.*)" + self.str_hour.get() + ':' + self.str_minute.get() + ':' + self.str_second.get() + "(.*\n)" + f"(#.*\n){{{int(self.str_lines.get())}}}",
                        self.file)
                    if matching != None:
                        self.result = matching.group()
                        self.text_prev.delete("1.0", tkinter.END)
                        self.text_prev.insert(tkinter.END, self.result)
                        self.text_prev.update()
                    else:
                        self.text_prev.insert(tkinter.END, "未匹配到任何数据,开始尝试第三次匹配\n")
                        matching = re.search(
                            "(#.*)" + self.str_date.get().replace("-0",
                                                                  '-') + " " + self.str_hour.get() + ':' + self.str_minute.get() + ':' + self.str_second.get() + "(.*\n)" + f"(#.*\n){{{int(self.str_lines.get())}}}",
                            self.file)
                        if matching != None:
                            self.result = matching.group()
                            self.text_prev.delete("1.0", tkinter.END)
                            self.text_prev.insert(tkinter.END, self.result)
                            self.text_prev.update()
                        else:
                            self.text_prev.insert(tkinter.END, "未匹配到任何数据,匹配结束\n")
            self.text_prev.see(tkinter.END)
            self.write_file()  # --------------------注意这里有自动

    def write_file(self, alpha=None):
        target_file = self.str_target_dir.get() + "/" + str(
            self.target_file_index).zfill(
            3) + "-" + self.str_oprate.get() + "-" + self.str_posite.get() + "-" + self.str_apower.get() + "-" + self.str_flow.get() + ".txt"
        with open(target_file, "w", encoding="utf-8") as t_f:
            self.text_prev.insert(tkinter.END, f"数据将存储在：{target_file}\n")
            self.text_prev.see(tkinter.END)
            r = t_f.write(self.result)
            self.text_prev.insert(tkinter.END, f"数据保存完毕{r}\n")
            self.text_prev.see(tkinter.END)

    def select_file(self, event=None):
        self.str_source_file.set(
            os.path.join(self.str_source_dir.get(), self.file_list[self.listbox.curselection()[0]]))

    def auto_do(self):
        timetable = openpyxl.load_workbook(
            r"D:\20250616 辽宁清原抽蓄热力学\20250706 低压侧自动化处理\20250704 输出数据整理.xlsx", True)
        worksheet = timetable.worksheets[0]
        for index_line, line in enumerate(worksheet.iter_rows()):
            if index_line + 1 != 1:
                self.str_date.set(line[0].value.strftime("%Y-%m-%d").strip())
                self.str_oprate.set(line[3].value.strip())
                self.str_posite.set(os.path.basename(self.str_source_file.get())[0:-4])
                self.str_apower.set(line[4].value)
                self.str_flow.set(line[5].value)
                self.str_hour.set(line[1].value.strftime("%H:%M:%S").split(":")[0].strip())
                self.str_minute.set(line[1].value.strftime("%H:%M:%S").split(":")[1].strip())
                self.str_second.set(line[1].value.strftime("%H:%M:%S").split(":")[2].strip())
                self.target_file_index = index_line
                if line[2].value < line[1].value:
                    end_time = datetime.datetime.combine(line[0].value + datetime.timedelta(days=1), line[2].value)
                else:
                    end_time = datetime.datetime.combine(line[0].value, line[2].value)
                start_time = datetime.datetime.combine(line[0].value, line[1].value)
                dt = (end_time - start_time).seconds
                self.str_lines.set(str(dt))
                self.cut_file()

    def main_window(self):
        root = tkinter.Tk()
        root.title("Txt Cut")
        root.resizable(False, False)

        root.bind("<Return>", self.cut_file)

        self.str_source_dir = tkinter.StringVar()  # 数据文件夹
        self.str_target_dir = tkinter.StringVar()  # 目标文件夹
        self.str_source_file = tkinter.StringVar()  # 数据文件名
        self.str_oprate = tkinter.StringVar()  # 工况点
        self.str_posite = tkinter.StringVar()  # 测点
        self.str_apower = tkinter.StringVar()  # 有功
        self.str_flow = tkinter.StringVar()  # 流量
        self.str_date = tkinter.StringVar()  # 日期/表达式
        self.str_hour = tkinter.StringVar()  # 时
        self.str_minute = tkinter.StringVar()  # 分
        self.str_second = tkinter.StringVar()  # 秒
        self.str_lines = tkinter.StringVar()  # 行数

        Frm_input = tkinter.Frame(root)
        Frm_prevw = tkinter.Frame(root)
        Frm_buton = tkinter.Frame(root)
        Frm_files = tkinter.Frame(root)

        tkinter.Label(Frm_input, text="源文件夹").grid(row=0, column=0)
        tkinter.Button(Frm_input, text="浏览", command=self.read_file).grid(row=0, column=1, sticky=tkinter.EW)
        tkinter.Entry(Frm_input, textvariable=self.str_source_dir).grid(row=1, column=0, columnspan=2,
                                                                        sticky=tkinter.EW)
        tkinter.Label(Frm_input, text="目标位置").grid(row=2, column=0)
        tkinter.Button(Frm_input, text="浏览", command=self.set_target).grid(row=2, column=1, sticky=tkinter.EW)
        tkinter.Entry(Frm_input, textvariable=self.str_target_dir).grid(row=3, column=0, columnspan=2,
                                                                        sticky=tkinter.EW)
        tkinter.Entry(Frm_input, textvariable=self.str_oprate).grid(row=4, column=0)
        tkinter.Entry(Frm_input, textvariable=self.str_posite).grid(row=4, column=1)
        tkinter.Entry(Frm_input, textvariable=self.str_apower).grid(row=5, column=0)
        tkinter.Entry(Frm_input, textvariable=self.str_flow).grid(row=5, column=1)
        tkinter.Label(Frm_input, text="日期/表达式").grid(row=6, column=0, columnspan=2)
        tkinter.Entry(Frm_input, textvariable=self.str_date).grid(row=7, column=0, columnspan=2, sticky=tkinter.EW)
        tkinter.Entry(Frm_input, textvariable=self.str_hour).grid(row=8, column=0)
        tkinter.Entry(Frm_input, textvariable=self.str_minute).grid(row=8, column=1)
        tkinter.Entry(Frm_input, textvariable=self.str_second).grid(row=9, column=0)
        tkinter.Entry(Frm_input, textvariable=self.str_lines).grid(row=9, column=1)

        tkinter.Entry(Frm_files, textvariable=self.str_source_file).grid(row=0, column=0, columnspan=2,
                                                                         sticky=tkinter.EW)
        self.listbox = tkinter.Listbox(Frm_files, width=40)
        self.listbox.grid(row=1, column=0, sticky=tkinter.NSEW, columnspan=2)
        self.listbox.bind("<Double-Button-1>", self.select_file)
        tkinter.Label(Frm_prevw, text="预览").grid(row=0, column=0, columnspan=2)
        self.text_prev = tkinter.Text(Frm_prevw, height=20)
        scb_prev = tkinter.Scrollbar(Frm_prevw, command=self.text_prev.yview)
        self.text_prev.grid(row=1, column=0, sticky=tkinter.NSEW)
        scb_prev.grid(row=1, column=1, sticky=tkinter.NS)
        self.text_prev.configure(yscrollcommand=scb_prev.set)

        menubar = tkinter.Menu(root)
        menubar.add_command(label="剪切并保存", command=self.cut_file)
        menubar.add_command(label="自动执行", command=self.auto_do)
        ttk.Menubutton(Frm_files, text="剪切并保存", menu=menubar).grid(row=2, column=0, sticky=tkinter.EW)
        ttk.Button(Frm_files, text="保存", command=self.write_file).grid(row=2, column=1, sticky=tkinter.EW)

        Frm_input.grid(row=0, column=0, sticky=tkinter.EW)
        Frm_files.grid(row=0, column=1, sticky=tkinter.NSEW)
        Frm_prevw.grid(row=1, column=0, columnspan=2)
        Frm_buton.grid(row=2, column=0, columnspan=2)

        root.mainloop()


myapp = TxtCut()
myapp.main_window()
